package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.EnterpriseOutfallValveAlarmMapper;
import com.bf.electroplating.pojo.entity.EnterpriseOutfallValve;
import com.bf.electroplating.pojo.entity.EnterpriseOutfallValveAlarm;
import com.bf.electroplating.pojo.entity.EnterpriseOutfallValveInfo;
import com.bf.electroplating.service.IEnterpriseOutfallValveAlarmService;
import com.bf.electroplating.util.HJ212FactorCodeMapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * 企业排污阀告警记录表 服务实现类
 *
 * @author system
 * @since 2025-10-09
 */
@Slf4j
@Service
public class EnterpriseOutfallValveAlarmServiceImpl extends ServiceImpl<EnterpriseOutfallValveAlarmMapper, EnterpriseOutfallValveAlarm> implements IEnterpriseOutfallValveAlarmService {

    @Override
    public void checkAndGenerateAlarm(EnterpriseOutfallValve valve, EnterpriseOutfallValveInfo valveInfo, Map<String, String> valueMap) {
        try {
            LocalDateTime now = LocalDateTime.now();

            // 检查流量超标
            if (valve.getFlowRateAvg() != null && valveInfo.getFlowAlarmThreshold() != null) {
                if (valve.getFlowRateAvg().compareTo(valveInfo.getFlowAlarmThreshold()) > 0) {
                    createAlarm(valve, valveInfo, "FLOW_EXCEED", "WARNING",
                            valve.getFlowRateAvg().toString(),
                            valveInfo.getFlowAlarmThreshold().toString(),
                            "流量超标：当前值" + valve.getFlowRateAvg() + "m³/h，阈值" + valveInfo.getFlowAlarmThreshold() + "m³/h",
                            now);
                }
            }

            // 检查PH异常
            if (valve.getPhAvg() != null && valveInfo.getPhMinThreshold() != null && valveInfo.getPhMaxThreshold() != null) {
                if (valve.getPhAvg().compareTo(valveInfo.getPhMinThreshold()) < 0 ||
                        valve.getPhAvg().compareTo(valveInfo.getPhMaxThreshold()) > 0) {
                    createAlarm(valve, valveInfo, "PH_ABNORMAL", "WARNING",
                            valve.getPhAvg().toString(),
                            valveInfo.getPhMinThreshold() + "~" + valveInfo.getPhMaxThreshold(),
                            "PH值异常：当前值" + valve.getPhAvg() + "，正常范围" + valveInfo.getPhMinThreshold() + "~" + valveInfo.getPhMaxThreshold(),
                            now);
                }
            }

            // 检查COD超标
            if (valve.getCodAvg() != null && valveInfo.getCodAlarmThreshold() != null) {
                if (valve.getCodAvg().compareTo(valveInfo.getCodAlarmThreshold()) > 0) {
                    createAlarm(valve, valveInfo, "COD_EXCEED", "ERROR",
                            valve.getCodAvg().toString(),
                            valveInfo.getCodAlarmThreshold().toString(),
                            "COD超标：当前值" + valve.getCodAvg() + "mg/L，阈值" + valveInfo.getCodAlarmThreshold() + "mg/L",
                            now);
                }
            }

            // 检查设备故障（根据Flag标志位）
            if (HJ212FactorCodeMapping.isAbnormalFlag(valve.getFlowRateFlag()) ||
                    HJ212FactorCodeMapping.isAbnormalFlag(valve.getPhFlag()) ||
                    HJ212FactorCodeMapping.isAbnormalFlag(valve.getCodFlag())) {
                
                StringBuilder desc = new StringBuilder("设备数据异常：");
                if (HJ212FactorCodeMapping.isAbnormalFlag(valve.getFlowRateFlag())) {
                    desc.append("流量[").append(HJ212FactorCodeMapping.getFlagDescription(valve.getFlowRateFlag())).append("] ");
                }
                if (HJ212FactorCodeMapping.isAbnormalFlag(valve.getPhFlag())) {
                    desc.append("PH[").append(HJ212FactorCodeMapping.getFlagDescription(valve.getPhFlag())).append("] ");
                }
                if (HJ212FactorCodeMapping.isAbnormalFlag(valve.getCodFlag())) {
                    desc.append("COD[").append(HJ212FactorCodeMapping.getFlagDescription(valve.getCodFlag())).append("] ");
                }

                createAlarm(valve, valveInfo, "DEVICE_FAULT", "ERROR",
                        "", "", desc.toString(), now);
            }

            // 检查设备离线（如果当前状态为离线）
            if ("OFFLINE".equals(valve.getOnlineStatus())) {
                createAlarm(valve, valveInfo, "OFFLINE", "CRITICAL",
                        "离线", "在线",
                        "设备离线，最后监测时间：" + valve.getMonitoringTime(),
                        now);
            }

        } catch (Exception e) {
            log.error("检查排污阀告警失败：{}", e.getMessage(), e);
        }
    }

    /**
     * 创建告警记录
     */
    private void createAlarm(EnterpriseOutfallValve valve, EnterpriseOutfallValveInfo valveInfo,
                             String alarmType, String alarmLevel, String alarmValue,
                             String thresholdValue, String alarmDesc, LocalDateTime now) {
        try {
            // 检查是否已存在未处理的相同类型告警
            LambdaQueryWrapper<EnterpriseOutfallValveAlarm> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EnterpriseOutfallValveAlarm::getValveId, valve.getId())
                    .eq(EnterpriseOutfallValveAlarm::getAlarmType, alarmType)
                    .eq(EnterpriseOutfallValveAlarm::getAlarmStatus, "UNHANDLED");

            EnterpriseOutfallValveAlarm existingAlarm = this.getOne(queryWrapper);
            if (existingAlarm != null) {
                // 已存在未处理告警，不重复创建
                log.debug("排污阀{}已存在未处理的{}告警，不重复创建", valve.getDeviceName(), alarmType);
                return;
            }

            // 创建新告警
            EnterpriseOutfallValveAlarm alarm = new EnterpriseOutfallValveAlarm();
            alarm.setId(UUID.randomUUID().toString().replace("-", ""));
            alarm.setValveId(valve.getId());
            alarm.setValveName(valve.getDeviceName());
            alarm.setCompanyId(valve.getCompanyId());
            alarm.setCompanyName(valve.getCompanyName());
            alarm.setMnCode(valve.getMnCode());
            alarm.setAlarmType(alarmType);
            alarm.setAlarmLevel(alarmLevel);
            alarm.setAlarmValue(alarmValue);
            alarm.setThresholdValue(thresholdValue);
            alarm.setAlarmDesc(alarmDesc);
            alarm.setAlarmStartTime(now);
            alarm.setAlarmStatus("UNHANDLED");
            alarm.setCreateTime(now);

            this.save(alarm);
            log.info("创建排污阀告警：{} - {}", valve.getDeviceName(), alarmDesc);

        } catch (Exception e) {
            log.error("创建告警记录失败：{}", e.getMessage(), e);
        }
    }
}

